<script setup lang="ts" name="PhoneInput">

interface Props {
  phone?: string;
  placeholder?: string;
}

const props = withDefaults(defineProps<Props>(), {
  phone: () => '',
  placeholder: () => '请输入手机号'
});

const input = ref(props.phone);

const emit = defineEmits(['update:phone']);

const formatPhoneNumber = (value: string): string => {
  const digits = value.replace(/\D/g, '');

  let formattedValue = digits.slice(0, 3);
  if (digits.length >= 4) {
    formattedValue += ` ${digits.slice(3, 7)}`;
  }
  if (digits.length >= 8) {
    formattedValue += ` ${digits.slice(7, 11)}`;
  }
  return formattedValue;
};

const parsePhoneNumber = (value: string): string => {
  return value.replace(/\D/g, '');
};

// 当编辑器内容改变时，通知父组件
const onInput = (newValue: string) => {
  emit('update:phone', newValue);
};

// 同步 phone 和 editorValue 的值
watchEffect(() => {
  if (props.phone !== input.value) {
    input.value = props.phone;
  }
});

</script>

<template>
  <el-input
    class="phone-input"
    :model-value="input"
    @update:model-value="onInput"
    :placeholder="props.placeholder"
    :formatter="formatPhoneNumber"
    :parser="parsePhoneNumber"
  />
</template>

<style scoped lang="scss">
.phone-input {
  width: 100%;
}
</style>